package com.sduept.nwld.dataserver.controller.daily;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.primefaces.PrimeFaces;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.TreeNode;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.entity.core.RecordAttachment;
import com.sduept.bigdata.document.services.RecordAttachmentManager;
import com.sduept.bigdata.fault.common.ParamDesc;
import com.sduept.bigdata.fault.protection.model.ProtectChannelAlarm;
import com.sduept.bigdata.fault.protection.service.ProtectChannelAlarmQueryManager;
import com.sduept.bigdata.risk.service.RiskAlarmMessageQueryManager;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.model.core.Equipment;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.cim.model.wires.ACLineSegment;
import com.sduept.cim.model.wires.Breaker;
import com.sduept.cim.model.wires.BusbarSection;
import com.sduept.cim.model.wires.Compensator;
import com.sduept.cim.model.wires.DcLinesegment;
import com.sduept.cim.model.wires.PowerTransformer;
import com.sduept.core.ParamManager;
import com.sduept.core.entity.SystemParameter;
import com.sduept.generator.ObjectId;
import com.sduept.message.entity.AlarmMessage;
import com.sduept.message.entity.AlarmMessageCheck;
import com.sduept.message.manager.AlarmMessageCheckManager;
import com.sduept.message.manager.AlarmMessageManager;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.manager.protection.AlarmMessageReceiverManager;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.utils.DateUtil;

@Named
@ViewScoped
public class AlarmMessageCheckController extends AbstractController {

	private static final long serialVersionUID = -5062504364827813597L;
	@Autowired
	private CommonDocumentProperties pros;
	@Autowired
	private AlarmMessageCheckManager checkManager;
	@Autowired
	private RiskAlarmMessageQueryManager riskAlarmManager;
	@Autowired
	private ProtectChannelAlarmQueryManager channelAlarmManager;
	@Autowired
	private ParamManager pcache;
	@Autowired
	private CimManager cimM;
	@Autowired
	private RecordAttachmentManager ram;
	@Autowired
	private AlarmMessageReceiverManager alarmMessageReceiverManager;
	@Autowired
	private AlarmMessageManager alarmMessageManager;

	private AlarmMessage alarm = new AlarmMessage();
	private AlarmMessageCheck alarmMsgCheck = new AlarmMessageCheck();
	private List<AlarmMessageCheck> alarmMsgChecks = new ArrayList<>();
	
	private List<AlarmMessageCheck> selectedChecks = null;
	
	private LazyDataModel<AlarmMessageCheck> model;

	List<SystemParameter> msgTypes = new ArrayList<SystemParameter>();

	private String msgStatusQuery; // 消息状态：未过期，已过期
	private String checkState; // 是否确认
	private String typeQuery;// 消息类型
	private Date queryDateStart;
	private Date queryDateEnd;
	private String contentQuery;// 消息内容
	
	private TreeNode primaryRoot;
	private TreeNode primarySelectedNode;
	private TreeNode secondaryRoot;
	private TreeNode secondarySelectedNode;
	private Boolean isChecked;
	private Substation subStation; //相关变电站

	/**
	 * 上传附件相关
	 */
	private List<RecordAttachment> attachments = new ArrayList<>();//附件 
	private List<String> repeatFileNames = new ArrayList<>();//重复的附件名称
	private List<UploadedFile> repeatFiles = new ArrayList<>();//重复的附件
	private String oid = null;
	private String path = null;
	private boolean fileExist = false;
	private StreamedContent file;
	
	
	@PostConstruct
	public void init() {
		getAllAlarmTypes();
		checkState = "all";
		msgStatusQuery = "";
		DateTime dt = new DateTime();
		queryDateEnd = dt.toDate();
		queryDateStart = dt.minusDays(30).toDate();
		initTable(msgStatusQuery, null, queryDateStart, queryDateEnd, null, null);
	}
	/**
	 * 获取所有的消息类型
	 */
	private void getAllAlarmTypes(){
		String allTypes = pcache.get(ParamDesc.RISK_ALARM_TYPES).getValue();
		StringTokenizer token = new StringTokenizer(allTypes, ",");
		while(token.hasMoreTokens()){
			SystemParameter param = pcache.get(token.nextToken());
			msgTypes.add(param);
		}
	}

	/**
	 * 根据消息类型获取其描述
	 * @param type
	 * @return
	 */
	public String getDescriptionText(String type) {
		SystemParameter param = pcache.get(type);
		if(null != param) {
			return param.getDescription();
		} else {
			return null;
		}
	}
	
	/**
	 * 根据异常告警，获得发生异常的设备
	 * @param alarmMessage
	 * @return
	 */
	public String getStationNameByCheck(AlarmMessageCheck alarmMessage) {
		return checkManager.getStationName(alarmMessage);
	}
	
	public String getCheckedStatus(Boolean isChecked) {
		if (isChecked) {
			return "已确认";
		} else {
			return "未确认";
		}
	}

	/**
	 * 初始化列表，查询全部
	 */
	private void initTable(final String msgStatusQuery, final String msgType, final Date pQueryDateStart, final Date pQueryDateEnd,
			final Boolean pCheckstate, final String pContent) {
		model = new LazyDataModel<AlarmMessageCheck>() {
			private static final long serialVersionUID = 6432560441960227351L;

			@Override
			public List<AlarmMessageCheck> load(int first, int pageSize, String sortField,
					SortOrder sortOrder, Map<String, Object> filters) {
				Integer msgStatus = StringUtils.isNotEmpty(msgStatusQuery) ? Integer.valueOf(msgStatusQuery) : null;
				alarmMsgChecks = checkManager.getCurrentAlarmMessageCheckByCondition(msgStatus, msgType,
						pQueryDateStart, pQueryDateEnd, pCheckstate, pContent, new int[] { first, first + pageSize });
				return alarmMsgChecks;
			}

			@Override
			public AlarmMessageCheck getRowData(String rowKey) {
				for (AlarmMessageCheck t : alarmMsgChecks) {
					if (t.getId().equals(rowKey)) {
						return t;
					}
				}
				return null;
			}

			@Override
			public Object getRowKey(AlarmMessageCheck object) {
				for (AlarmMessageCheck t : alarmMsgChecks) {
					if (t.getId().equals(object.getId())) {
						return t;
					}
				}
				return null;
			}
		};
		Integer msgStatus = StringUtils.isNotEmpty(msgStatusQuery) ? Integer.valueOf(msgStatusQuery) : null;
		long rowCount = checkManager.countByCondition(pQueryDateStart, pQueryDateEnd, msgStatus, msgType, pCheckstate, pContent);
		model.setRowCount((int) rowCount);
	}

	public void query() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
		String startTime = format.format(queryDateStart);
		String endTime = format2.format(queryDateEnd).concat(" 23:59:59");
		try {
			queryDateStart = format.parse(startTime);
			queryDateEnd = format.parse(endTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Boolean _checkState = null;
		if ("true".equals(checkState)) {
			_checkState = true;
		} else if ("false".equals(checkState)) {
			_checkState = false;
		}
		initTable(msgStatusQuery, typeQuery, queryDateStart, queryDateEnd, _checkState, contentQuery);
	}

	public void resetQuery() {
		checkState = null;
		DateTime dt = new DateTime();
		queryDateEnd = dt.toDate();
		queryDateStart = dt.minusDays(30).toDate();
		typeQuery = null;
		contentQuery = null;
		msgStatusQuery = "";
		initTable(msgStatusQuery, null, queryDateStart, queryDateEnd, null, contentQuery);
		selectedChecks = null;
	}

	/**
	 * 新建之前，给AlarmMessage和AlarmMessageCheck赋初始值
	 */
	public void preCreate() {
		alarm = new AlarmMessage();
		alarm.setMsgType(msgTypes.get(0).getId());
		alarm.setCreateTime(new Date());
		
		alarmMsgCheck = new AlarmMessageCheck();
		alarmMsgCheck.setChecker(getCurrentUser().getName());
		alarmMsgCheck.setCheckTime(new Date());
		alarmMsgCheck.setMsgTime(alarm.getCreateTime());
//		selectedChecks = null;
	}

	private void saveCreate() {
		SystemParameter param = pcache.get(alarm.getMsgType());
		Long timeLiness=Long.parseLong(param.getValue());
		alarm.setTimeliness(timeLiness);
		// 创建AlarmMessage
		AlarmMessage am = alarmMessageManager.createOrUpdate(alarm);
		// 根据AlarmMessage创建AlarmMessageCheck
		try {
			checkManager.createAlarmMessageCheckByAlarm(am, alarmMsgCheck);
			alarmMessageReceiverManager.sendMessage(alarmMsgCheck);
			addSuccessMessage("新增记录成功！");
		} catch (Exception e) {
			addErrorMessage("异常告警处理情况为空！");
		}
		query();
	}
	
	public void preEdit() {
		if(selectedChecks.size()==1) {
			alarmMsgCheck = selectedChecks.get(0);
			alarm = getAlarmByCheck(alarmMsgCheck);
			if(null == alarm) {
				// 当AlarmMessageCheck没有对应的AlarmMessage
				alarm = new AlarmMessage();
				alarm.setCreateTime(new Date());
				alarm.setContent(alarmMsgCheck.getMsgContent());
				alarm.setMsgType(alarmMsgCheck.getMsgType());
				alarm.setId(ObjectId.get().toString());
				SystemParameter param = pcache.get(alarm.getMsgType());
				Long timeLiness = Long.parseLong(param.getValue());
				alarm.setTimeliness(timeLiness);
			}
		} else {
			alarmMsgCheck = new AlarmMessageCheck();
		}
		if(null == alarmMsgCheck.getCheckTime()) {
			alarmMsgCheck.setCheckTime(new Date());
		}
		if(StringUtils.isEmpty(alarmMsgCheck.getChecker())) {
			alarmMsgCheck.setChecker(getCurrentUser().getName());
		}
	}
	
	private void saveEdit() {
		// 更新AlarmMessage
		if(selectedChecks.size()==1) {
			/**
			 * 如果消息手动设置为过期（即将timeliness置为0），则在保存的时候，其timeliness依旧为0，消息处于过期状态
			 * 消息未手动设置为过期状态时，要根据新的消息类型重新设置消息的timeliness的值
			 */
			if(0 != alarm.getTimeliness()) {
				SystemParameter param = pcache.get(alarm.getMsgType());
				Long timeLiness = Long.parseLong(param.getValue());
				alarm.setTimeliness(timeLiness);
			}
			alarm = alarmMessageManager.update(alarm);
			// 更新AlarmMessageCheck
			// 当编辑之前AlarmMessageCheck没有对应的AlarmMessage时，需要更新msgId
			alarmMsgCheck.setMsgId(alarm.getId());
			alarmMsgCheck.setMsgContent(alarm.getContent());
			alarmMsgCheck.setMsgTime(alarm.getCreateTime());
			alarmMsgCheck.setMsgType(alarm.getMsgType());
			checkManager.updateAlarmMessageCheck(alarmMsgCheck);
		} else {
			for (AlarmMessageCheck select : selectedChecks) {
				AlarmMessage alarm = getAlarmByCheck(select);
				if(null == alarm) {
					// 当AlarmMessageCheck没有对应的AlarmMessage
					alarm = new AlarmMessage();
					alarm.setCreateTime(new Date());
					alarm.setContent(select.getMsgContent());
					alarm.setMsgType(select.getMsgType());
					alarm.setId(ObjectId.get().toString());
					SystemParameter param = pcache.get(alarm.getMsgType());
					Long timeLiness = Long.parseLong(param.getValue());
					alarm.setTimeliness(timeLiness);
				} else {
					if(0 != alarm.getTimeliness()) {
						SystemParameter param = pcache.get(alarm.getMsgType());
						Long timeLiness = Long.parseLong(param.getValue());
						alarm.setTimeliness(timeLiness);
					}
				}
				alarm = alarmMessageManager.update(alarm);
				// 更新AlarmMessageCheck
				// 当编辑之前AlarmMessageCheck没有对应的AlarmMessage时，需要更新msgId
				select.setMsgId(alarm.getId());
				select.setMsgContent(alarm.getContent());
				select.setMsgTime(alarm.getCreateTime());
				select.setMsgType(alarm.getMsgType());
				select.setChecker(alarmMsgCheck.getChecker());
				select.setCheckResult(alarmMsgCheck.getCheckResult());
				select.setCheckTime(alarmMsgCheck.getCheckTime());
				select.setIsChecked(alarmMsgCheck.getIsChecked());
				checkManager.updateAlarmMessageCheck(select);
			}
		}
		addSuccessMessage("保存成功！");
		selectedChecks = null;
		query();
	}

	public void save() {
		if(selectedChecks!=null) {
			saveEdit();
		} else {
			saveCreate();
		}
	}
	
	public void deleteById() {
		for (AlarmMessageCheck selected : selectedChecks) {
			checkManager.deleteById(selected.getId());
			alarmMsgChecks.remove(selected);
		}
		addSuccessMessage("删除成功！");
		selectedChecks = null;
		query();
	}

	/**
	 * 确认该条记录
	 */
	public void checkedByHand() {
		for (AlarmMessageCheck selected : selectedChecks) {
			if (selected != null) {
				selected.setIsChecked(true);
				checkManager.saveAlarmMessageCheck(selected);
			}
		}
		selectedChecks = null;
	}

	public String getChannelAlarm(AlarmMessageCheck msg) {
		String s = "无通道告警信息";
		if(msg == null) {
			return s;
		}
		List<ProtectChannelAlarm> channelAlarm = channelAlarmManager.getProtectChannelAlarmByMsg(msg);
		if(channelAlarm.size() == 0) {
			return s;
		}
		s = "";
		for(int i=0;i<channelAlarm.size();i++) {
			if(i > 0) {
				s += "<br/>";
			}
			ProtectChannelAlarm a = channelAlarm.get(i);
			s += (i+1)+"、"+DateUtil.getStringDate(a.getTriggerTime(), DateUtil.pattern_ymdhms)
					+"<span style='margin-left:5px;'>"+a.getAlarmChannel()+"</span><br/>"
					+a.getAlarmObject()+"：<span style='color:red'>"+a.getName()+"</span>";
		}
		return s;
	}
	
	public AlarmMessage getAlarmByCheck(AlarmMessageCheck check) {
		AlarmMessage alarm = new AlarmMessage();
		if(null != check) {
			String msgId = check.getMsgId();
			if(StringUtils.isNotEmpty(msgId)) {
				alarm = riskAlarmManager.getAlarmMessageById(msgId);
			} 
		}
		return alarm;
	}
	
	//************************* 选择变电站、一次设备、二次设备相关代码  *************************

	/**
	 * 选择变电站后，将AlarmMessage的一、二次设备信息清空
	 * @param event
	 */
	public void onSubstationChosen(SelectEvent event) {
		subStation = (Substation) event.getObject();
		alarm.setStationId(subStation.getId());
		alarm.setStationName(subStation.getName());
		alarm.setPrimaryId(null);
		alarm.setPrimaryName(null);
		alarm.setSecondaryId(null);
		alarm.setSecondaryName(null);
		genMsgContent();
	}
	
	/** 
	 * 初始化一次设备选择树
	 */
	public void initPrimaryTree() {
		primaryRoot = new LibTreeNode("Root",null);
		LibTreeNode root = new LibTreeNode();
		Substation station = new Substation();
		// 如果subStation相关变电站不为空，则以选中的变电站构造一次设备树，否则为编辑状态，以当前AlarmMessage的变电站构造一次设备树
		if(null != subStation) {
			station = subStation;
		} else if(StringUtils.isNotEmpty(alarm.getStationId())) {
			station = cimM.getStationById(alarm.getStationId());
		} else {
			return;
		}
		root = new LibTreeNode("station",station,primaryRoot);
		if(null != station) {
			LibTreeNode busbarRoot = new LibTreeNode("type","母线",root);
			List<BusbarSection> buasbarList = cimM.getBusbarSectionsByStationId(station.getId());
			for (BusbarSection busbarSection : buasbarList) {
				new LibTreeNode("equipment", busbarSection, busbarRoot);
			}
			LibTreeNode dcRoot = new LibTreeNode("type","直流线路",root);
			List<DcLinesegment> dclines = cimM.getDcLineSegmentsBySubstation(station.getId());
			for (DcLinesegment dcLinesegment : dclines) {
				new LibTreeNode("equipment", dcLinesegment, dcRoot);
			}
			LibTreeNode acRoot = new LibTreeNode("type","交流线路",root);
			List<ACLineSegment> acLines = cimM.getAcLineSegmentsBySubstation(station.getId());
			for (ACLineSegment acLine : acLines) {
				new LibTreeNode("equipment", acLine, acRoot);
			}
			LibTreeNode transRoot = new LibTreeNode("type","变压器",root);
			List<PowerTransformer> transList = cimM.getPowerTransformersByStationId(station.getId());
			for (PowerTransformer powerTransformer : transList) {
				new LibTreeNode("equipment", powerTransformer, transRoot);
			}
			LibTreeNode comRoot = new LibTreeNode("type","电抗器",root);
			List<Compensator> compList = cimM.getCompensatorsByStationId(station.getId());
			for (Compensator compensator : compList) {
				new LibTreeNode("equipment", compensator, comRoot);
			}
			LibTreeNode breakerRoot = new LibTreeNode("type","断路器",root);
			List<Breaker> breakers = cimM.getBreakersByStationId(station.getId());
			for (Breaker breaker : breakers) {
				new LibTreeNode("equipment", breaker, breakerRoot);
			}
		}
		root.setExpanded(true);
	}
	/**
	 * 初始化二次设备选择树
	 */
	public void initSecondaryTree() {
		secondaryRoot = new LibTreeNode("Root",null);
		LibTreeNode root = new LibTreeNode();
		Substation station = new Substation();
		// 如果选中变电站节点，则以选中的变电站构造二次设备树，否则为编辑状态，以当前AlarmMessage的变电站构造二次设备树
		if(null != subStation) {
			station = subStation;
		} else if(StringUtils.isNotEmpty(alarm.getStationId())) {
			station = cimM.getStationById(alarm.getStationId());
		} else {
			return;
		}
		root = new LibTreeNode("station",station,secondaryRoot);
		if (null != station) {
			LibTreeNode protectRoot = new LibTreeNode("type","保护设备",root);
			List<ProtectionEquipment> protectionEquipments = cimM.getProtectionEquipmentsByStationId(station.getId());
			for (ProtectionEquipment protectionEquipment : protectionEquipments) {
				new LibTreeNode("equipment", protectionEquipment, protectRoot);
			}
		}
		root.setExpanded(true);
	}


	public void onPrimaryNodeExpand(NodeExpandEvent event) {}
	
	public void onSecondaryNodeExpand(NodeExpandEvent event) {}
	
	public void onPrimaryNodeSelect(NodeSelectEvent event) {
		if("equipment".equals(event.getTreeNode().getType())) {
			primarySelectedNode = event.getTreeNode();
		}
	}
	
	public void onSecondaryNodeSelect(NodeSelectEvent event) {
		if("equipment".equals(event.getTreeNode().getType())) {
			secondarySelectedNode = event.getTreeNode();
		}
	}
	
	/**
	 * 选定相关一次设备后，设置AlarmMessage的相应值
	 */
	public void savePrimary() {
		if(null != primarySelectedNode) {
			Equipment primary = (Equipment) primarySelectedNode.getData();
			alarm.setPrimaryId(primary.getId());
			alarm.setPrimaryName(primary.getName());
		}
		genMsgContent();
	}

	/**
	 * 如果手动输入一次设备，则一次设备id置为null
	 */
	public void editPrimaryName() {
		alarm.setPrimaryId(null);
		genMsgContent();
	}

	/**
	 * 选定相关二次设备后，设置AlarmMessage的相应值
	 */
	public void saveSecondary() {
		if(null != secondarySelectedNode) {
			ProtectionEquipment secondary = (ProtectionEquipment) secondarySelectedNode.getData();
			alarm.setSecondaryId(secondary.getId());
			alarm.setSecondaryName(secondary.getName());
		}
		genMsgContent();
	}
	
	/**
	 * 如果手动输入二次设备，则二次设备id置为null
	 */
	public void editSecondaryName() {
		alarm.setSecondaryId(null);
		genMsgContent();
	}

	public void genMsgContent() {
		String content = "";
		if(StringUtils.isNotEmpty(alarm.getStationName())) {
			content = alarm.getStationName();
		}
		if (StringUtils.isNotEmpty(alarm.getPrimaryName())) {
			content += "/"+alarm.getPrimaryName();
		}
		if(StringUtils.isNotEmpty(alarm.getSecondaryName())) {
			content += "/"+alarm.getSecondaryName();
		}
		if(StringUtils.isNotEmpty(alarm.getMsgType())) {
			SystemParameter param = pcache.get(alarm.getMsgType());
			if(null != param) {
				content += "，发生"+param.getDescription();
			}
		}
		alarm.setContent(content);
	}
	
	// *************************** 上传附件相关代码  ***************************
	
	/**
	 * 根据alarmMessageCheck的id获得附件
	 */
	public List<RecordAttachment> getAlarmAttachments(String alarmId) {
		return ram.getAttachmentsByOId(alarmId);
	}
	
	/**
	 * 删除附件
	 */
	public void removeFile(RecordAttachment record) {
		try {
			String removePath = pros.getDocumentPath() + record.getName();
			File f = new File(removePath);
			fileExist = f.exists();
			if (fileExist) {
				fileExist = false;
				f.delete();
			}
			ram.deleteRecordAttachment(record);
			addSuccessMessage("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("删除失败");
		}
		selectedChecks = null;
	}
	/**
	 * 下载附件
	 */
	public void fileDownloadView(String id) {
		RecordAttachment recordAttachment = ram.getAttachmentById(id);
		InputStream stream = null;
		file = null;
		try {
			stream = new FileInputStream(pros.getDocumentPath() + recordAttachment.getName());
		} catch (FileNotFoundException e1) {
			addErrorMessage("文件不存在，下载失败！");
			return;
		} finally {
			fileExist = stream != null;
		}
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		try {
			String agent = request.getHeader("User-Agent").toLowerCase();
			if (agent != null && (agent.indexOf("msie") != -1 || (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1))
					|| agent.indexOf("edge") != -1) {
				file = new DefaultStreamedContent(stream, "application/octet-stream", URLEncoder.encode(recordAttachment.getDescription(), "UTF-8"));
			} else {
				file = new DefaultStreamedContent(stream, "application/octet-stream", new String(recordAttachment.getDescription().getBytes("UTF-8"), "ISO8859-1"));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			if (file == null) {
				fileExist = false;
			}
		}
	}
	
	public void preUpLoadFile(String alarmId) {
 		oid = alarmId;
 		path = pros.getDocumentPath();
 		attachments = ram.getAttachmentsByOId(alarmId);
	}
	
	//上传附件
	public void handleFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		String fileName = file.getFileName();
		//检查有没有重名的文件
		for(RecordAttachment r:attachments) {
			if(fileName.equals(r.getDescription())) {
				repeatFileNames.add(fileName);
				repeatFiles.add(file);
				openRepeatDialog();
				return;
			}
		}
		saveFile(file);
	}
	/**
	 * 有相同的文件时，删掉已有文件，保存新文件
	 */
	public void replaceFile() {
		for(int i=0;i<repeatFileNames.size();i++) {
			String repeatFileName=repeatFileNames.get(i);
			UploadedFile repeatFile=repeatFiles.get(i);
			for(RecordAttachment ra:attachments) {
				if(repeatFileName.equals(ra.getDescription())) {
					removeFile(ra);
					break;
				}
			}
			saveFile(repeatFile);
		}
		repeatFileNames.clear();
		repeatFiles.clear();
	}
	//不替换
	public void cancelReplaceFile() {
		repeatFileNames.clear();
		repeatFiles.clear();
	}
	
	/**
	 * 上传附件
	 */
	public void saveFile(UploadedFile file) {
		String houzhuiming = file.getFileName().substring(file.getFileName().lastIndexOf("."));
		String id = ObjectId.get().toString();
		String dirFileName = id + houzhuiming;
		String filePath = path;
		if (filePath == null)
			filePath = pros.getDocumentPath() + dirFileName;
		else
			filePath += dirFileName;
		try {
			FileOutputStream fos = new FileOutputStream(filePath);
			fos.write(file.getContents());
			fos.close();
			RecordAttachment ra = new RecordAttachment();
			ra.setName(dirFileName);
			ra.setDescription(file.getFileName());
			ra.setOid(oid);
			ra.setType("异常告警消息附件");
			ra.setUploadDate(new Date());
			ra.setPath(filePath);
			ra.setUploadPerson(getCurrentUser().getName());
			ra = ram.createOrUpdateRecordAttachment(ra);
		} catch (IOException ee) {
			ee.printStackTrace();
		}
		addSuccessMessage("附件上传成功，请确认");
	}

	//重复提示
	public void openRepeatDialog() {
		PrimeFaces.current().ajax().update("fileUploadForm:repeatDlg");
		PrimeFaces.current().executeScript("PF('repeatDlg').show();");
	}

	public String getTypeQuery() {
		return typeQuery;
	}

	public void setTypeQuery(String typeQuery) {
		this.typeQuery = typeQuery;
	}

	public Date getQueryDate1() {
		return queryDateStart;
	}

	public void setQueryDate1(Date queryDate1) {
		this.queryDateStart = queryDate1;
	}

	public Date getQueryDate2() {
		return queryDateEnd;
	}

	public void setQueryDate2(Date queryDate2) {
		this.queryDateEnd = queryDate2;
	}

	public LazyDataModel<AlarmMessageCheck> getModel() {
		return model;
	}

	public void setModel(LazyDataModel<AlarmMessageCheck> model) {
		this.model = model;
	}

	public Date getQueryDateStart() {
		return queryDateStart;
	}

	public void setQueryDateStart(Date queryDateStart) {
		this.queryDateStart = queryDateStart;
	}

	public Date getQueryDateEnd() {
		return queryDateEnd;
	}

	public void setQueryDateEnd(Date queryDateEnd) {
		this.queryDateEnd = queryDateEnd;
	}

	public String getCheckState() {
		return checkState;
	}

	public void setCheckState(String checkState) {
		this.checkState = checkState;
	}

	public TreeNode getPrimaryRoot() {
		return primaryRoot;
	}

	public void setPrimaryRoot(TreeNode primaryRoot) {
		this.primaryRoot = primaryRoot;
	}

	public TreeNode getPrimarySelectedNode() {
		return primarySelectedNode;
	}

	public void setPrimarySelectedNode(TreeNode primarySelectedNode) {
		this.primarySelectedNode = primarySelectedNode;
	}

	public TreeNode getSecondaryRoot() {
		return secondaryRoot;
	}

	public void setSecondaryRoot(TreeNode secondaryRoot) {
		this.secondaryRoot = secondaryRoot;
	}

	public TreeNode getSecondarySelectedNode() {
		return secondarySelectedNode;
	}

	public void setSecondarySelectedNode(TreeNode secondarySelectedNode) {
		this.secondarySelectedNode = secondarySelectedNode;
	}

	public String getContentQuery() {
		return contentQuery;
	}

	public void setContentQuery(String contentQuery) {
		this.contentQuery = contentQuery;
	}
	
	public Boolean getIsChecked() {
		return isChecked;
	}

	public void setIsChecked(Boolean isChecked) {
		this.isChecked = isChecked;
	}

	public AlarmMessage getAlarm() {
		return alarm;
	}

	public void setAlarm(AlarmMessage alarm) {
		this.alarm = alarm;
	}

	public List<SystemParameter> getMsgTypes() {
		return msgTypes;
	}

	public void setMsgTypes(List<SystemParameter> msgTypes) {
		this.msgTypes = msgTypes;
	}

	public String getMsgStatusQuery() {
		return msgStatusQuery;
	}

	public void setMsgStatusQuery(String msgStatusQuery) {
		this.msgStatusQuery = msgStatusQuery;
	}

	public boolean isFileExist() {
		return fileExist;
	}

	public void setFileExist(boolean fileExist) {
		this.fileExist = fileExist;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public AlarmMessageCheck getAlarmMsgCheck() {
		return alarmMsgCheck;
	}
	
	public void setAlarmMsgCheck(AlarmMessageCheck alarmMsgCheck) {
		this.alarmMsgCheck = alarmMsgCheck;
	}
	
	public List<AlarmMessageCheck> getSelectedChecks() {
		return selectedChecks;
	}
	
	public void setSelectedChecks(List<AlarmMessageCheck> selectedChecks) {
		this.selectedChecks = selectedChecks;
	}
	
}
